<?php


namespace App\HttpController\Admin;

use App\Consts\RedisKey;
use App\Middleware\AuthMiddleware;
use App\Model\Admin;
use App\Utility\Response;
use EasySwoole\EasySwoole\Config;
use EasySwoole\RedisPool\Redis;
use App\Functions\PHPGangstaGoogleAuthenticator;
use App\Model\SystemConfig;

class Manager extends AdminBaseController
{

    public function index(){

        $page    = $this->request()->getRequestParam('page')?:1;
        $page_size = $this->request()->getRequestParam('page_size')?:20;
        
        $model = Admin::create()->alias('au')
            ->where('au.role_id',1,'>')
            ->join('dm_role as r','au.role_id=r.id','left')
            ->field('au.id,username,role_id,avatar,ip,city,au.state,r.name')
            ->limit($page_size * ($page - 1), $page_size)
            ->withTotalCount();
            
        $list = $model->all();
        
        $total = $model->lastQueryResult()->getTotalCount();

        return $this->returnData(200,['list'=>$list,'total'=>$total]);

    }

    public function create(){


        try {
            $data = $this->request()->getRequestParam();
            $data['password'] = md5( $data['password']);
            if($this->request()->getUploadedFiles()){
                $imgs = ['avatar'=> 'system_upload' ];
                foreach ($imgs as $formKey => $module){
                    $fileName = $this->uploadFile($formKey,$module);
                    if($fileName ){
                        $data[$formKey] = $fileName;
                    }
                }
            }

            $res = Admin::create()->data($data)->save();
            if($res){

                return $this->returnData(200);
            }
            return $this->returnData(400);

        }catch (\Exception $e){

            return $this->returnData(400,[],$e->getMessage());
        }
    }


    public function edit(){
        try {
            $data = $this->request()->getRequestParam();
            $id = $data['id'];
            unset($data['id']);
            if($data['password']){
                $data['password'] = md5(  $data['password']);
            }
            if($this->request()->getUploadedFiles()){
                $imgs = ['avatar'=> 'system_upload' ];
                foreach ($imgs as $formKey => $module){
                    $fileName = $this->uploadFile($formKey,$module);
                    if($fileName ){
                        $data[$formKey] = $fileName;
                    }
                }
            }

            $res = Admin::create()->where(['id'=> $id])->update($data);
            if($res){

                return $this->returnData(200);
            }
            return $this->returnData(400);

        }catch (\Exception $e){

            return $this->returnData(400,[],$e->getMessage());
        }

    }


    public function editInfo(){

        try {

            $data = $this->request()->getRequestParam();
            if($data['password']){
                $data['password'] = md5(  $data['password']);
            }
            if($this->request()->getUploadedFiles()){
                $imgs = ['avatar'=> 'system_upload' ];
                foreach ($imgs as $formKey => $module){
                    $fileName = $this->uploadFile($formKey,$module);
                    if($fileName ){
                        $data[$formKey] = $fileName;
                    }
                }
            }
            unset($data['role_id']);
            unset($data['state']);
            
            if(!empty($data['gv_code'])){
                $redis = Redis::defer('redis');
                $secret = $redis->get(RedisKey::GV_CODE.$this->getUserId());
                
                if(!$secret){
                    return $this->returnData(500);
                }
                
                $ga = new PHPGangstaGoogleAuthenticator();
                
                $checkResult = $ga->verifyCode($secret, $data['gv_code'],8);
                if ($checkResult) {
                    $data['gv_code'] = $secret;
                    $redis->del(GV_CODE.$this->getUserId());
                }else{
                    return $this->returnData(1008);
                }
            }
            
            $res = Admin::create()->where(['id'=> $this->getUserId()])->update($data);
            if($res){
                return $this->returnData(200,['avatar' => $data[$formKey]]);
            }
            return $this->returnData(400);

        }catch (\Exception $e){

            return $this->returnData(400,[],$e->getMessage());
        }

    }

    /**
     * 获取谷歌验证码
     * @return string
     */
    public function gvCode()
    {
        $ga = new PHPGangstaGoogleAuthenticator();
        
        $user = Admin::create()->where(['id'=> $this->getUserId()])->get();
        
        $secret = $ga->createSecret();
        
        $redis = Redis::defer('redis');
        
        $redis->set(RedisKey::GV_CODE.$this->getUserId(),$secret);
        
        $name = SystemConfig::create()->field('value_')->where(['key_name'=>'goole_verification_code'])->scalar();
        
        $qrCodeUrl = $ga->getQRCodeGoogleUrl($name.':'.$user->username, $secret,$name);
        
        return $this->returnData(200,['url'=>$qrCodeUrl,'user'=>$user]);
    }
    
    
}